import React, { useEffect } from "react";
import { message } from 'antd';
const e = React.createElement;
import Vditor from "vditor";

export type VditorEditorType = {
    moutId?: string;
    initValue?: string;
    toolbar?: string[];
    inputChange?: (value: string) => void,
    afterChange?: (value: Vditor) => void,
}

/**
 * Vditor编辑器
 * @param props 属性值
 */
const VditorEditor = (props: VditorEditorType) => {
    const { moutId, initValue, toolbar, inputChange, afterChange } = props;

    //初始化编辑器
    useEffect(() => {
        const vditor = new Vditor(moutId || 'vditor', {
            width: '100%',
            height: '100%',
            minHeight: 500,
            toolbar: toolbar || [
                "emoji", "headings", "bold", "italic", "strike", "link", "|",
                "list", "ordered-list", "check", "outdent", "indent", "|",
                "quote", "line", "code", "inline-code", "insert-before", "insert-after", "|",
                "upload", "record", "table", "|",
                "undo", "redo", "|",
                "fullscreen", "edit-mode",
            ],
            toolbarConfig: {
                pin: true,
            },
            outline: {
                enable: true,
                position: 'left'
            },
            preview: {
                hljs: {
                    enable: true,
                    style: 'native',
                    lineNumber: true
                },
                actions: []
            },
            mode: 'sv',
            cache: {
                enable: true,
            },
            input: inputChange || undefined,
            after() {
                if (initValue) {
                    vditor.setValue(initValue);
                }
                if (afterChange) {
                    afterChange(vditor);
                }
            },
        });

        // 监听键盘按下事件
        const vditorE = document.getElementById(moutId || 'vditor');
        if (vditorE) {
            vditorE.onkeydown = function (event) {
                // 判断 Ctrl+S
                if (event.ctrlKey == true
                    && (event.keyCode == 83 || event.key == '83')) {
                    message.info('保存成功！');
                    // 或者 return false;
                    event.preventDefault();
                }
            }
        }
    }, []);
    return <>
        {e('div', { id: 'vditor' })}
    </>;
};

export default VditorEditor;